package com.smart.ssm.service.impl;

import com.smart.ssm.entity.Carts;
import com.smart.ssm.exception.ServiceException;
import com.smart.ssm.mapper.CartsMapper;
import com.smart.ssm.reqeust.CartsReqeustParams;
import com.smart.ssm.service.CartsService;
import com.smart.ssm.utils.ColaBeanUtils;
import com.smart.ssm.vo.CartsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.smart.ssm.utils.ErrorStatus.SERVICE_ERROR;

@Service
public class CartsServiceImpl implements CartsService {
    @Resource
    CartsMapper cartsMapper;

    @Override
    public int saveCarts(CartsReqeustParams cartsReqeustParams) {
        //设计请求参数跟持久化对象的转化问题
        int temp = 0;
        try {
            Carts carts = cartsMapper.selectByUserIdAndProductId(cartsReqeustParams.getUserId(), cartsReqeustParams.getProductId());
            // 判断用户的购物车中是否存在该条记录
            if (carts != null) {
                int num = carts.getNum() + cartsReqeustParams.getNum();
                temp = cartsMapper.updateById(carts.getCartsId(), num);
            } else {
                carts = new Carts();
                /**
                 * 将对象的属性拷贝到另一个对象
                 * 1. 属性类型名称要保持一致
                 * 参数
                 * 参数 要拷贝的的对象
                 * 参数  目标对象
                 */
                BeanUtils.copyProperties(cartsReqeustParams, carts);
                temp = cartsMapper.insert(carts);
            }
        } catch (Exception e) {
            throw new ServiceException(SERVICE_ERROR.getMessage(), SERVICE_ERROR.getStatus());
        }
        return temp;
    }

    /**
     * 程序员应该业务不是而技术
     *
     * @param uid
     * @return
     */
    @Override
    public List<CartsVo> findAllCarts(int uid) {
        //
        List<Carts> carts = cartsMapper.selectList(uid);
//      BeanUtils 支持对象 不支持list
        List<CartsVo> cartsVos = ColaBeanUtils.copyListProperties(carts, CartsVo::new);
        return cartsVos;
    }
}
